package com.vega.user.thrift;

import com.vega.thrift.message.MessageService;
import com.vega.thrift.user.UserService;
import org.apache.thrift.TServiceClient;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TFramedTransport;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * 功能描述: <br>
 * 所属包名: com.vega.user.thrift<br>
 * 创建人　: 白剑<br>
 * 创建时间: 05/07/2018 21:15 Monday<br>
 * 当前版本: 1.0<br>
 * 修改历史: <br>
 * 修改时间　　　　　修改人　　　　　版本变更　　　　　修改说明<br>
 * -----------------------------------------------------<br>
 * <br>
 */
@Component
public class ServiceProvider {

    @Value("${thrift.user.ip}")
    private String USER_SERVER_IP;
    @Value("${thrift.user.port}")
    private int USER_SERVER_PORT;

    @Value("${thrift.message.ip}")
    private String MESSAGE_SERVER_IP;
    @Value("${thrift.message.port}")
    private int MESSAGE_SERVER_PORT;

    private int TIME_OUT = 3000;

    private enum ServiceType {
        USER,
        MESSAGE
    }

    public UserService.Client getUserService() {
        return getService(USER_SERVER_IP, USER_SERVER_PORT, ServiceType.USER);
    }

    public MessageService.Client getMessageService() {
        return getService(MESSAGE_SERVER_IP, MESSAGE_SERVER_PORT, ServiceType.MESSAGE);
    }

    private <T> T getService(String ip, int port, ServiceType serviceType) {

        TSocket socket = new TSocket(ip, port, TIME_OUT);
        // TODO 可能多次开启而没有关闭
        TTransport transport = new TFramedTransport(socket);
        try {
            transport.open();
        } catch (TTransportException e) {
            e.printStackTrace();
            return null;
        }
        TProtocol protocol = new TBinaryProtocol(transport);

        TServiceClient client = null;
        switch (serviceType) {
            case USER:
                client = new UserService.Client(protocol);
                break;
            case MESSAGE:
                client = new MessageService.Client(protocol);
                break;
            default:
                break;
        }
        return (T) client;
    }
}
